<?php
// +----------------------------------------------------------------------
// | Scallion 
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.scallion.top All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Liuxg < 420695648@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use think\Db;
use app\admin\model\class_blogModel;
use PHPExcel_IOFactory;
use PHPExcel;

class ClassController extends AdminBaseController
{
	
	public function class_timetable_view(){
		if($this->request->param()){
			$param = $this->request->param();
			$class = db('class')->where(['id'=>$param['id']])->find();
			$teacher = db('teacher')->where('id='.$class['teacher'])->find();
			$classroom = db('classroom')->where('id='.$class['classroom_id'])->find();
			$campus = db('campus')->where('id='.$classroom['campus_id'])->find();
			$class_timetable_data = db('class_timetable')->where('class_id='.$param['id'])->select()->toarray();
			if(!$class_timetable_data){
				$this->error($class['name'].'未排课！请先排课！');
			}
			else{
				foreach($class_timetable_data as $key=>$val){
					$assign_data[$key]['id'] = $val['id'];
					$assign_data[$key]['class_id'] = $val['class_id'];
					$assign_data[$key]['class_name'] = $class['name'];
					$assign_data[$key]['class_number'] = $val['class_number'];
					$assign_data[$key]['times'] = $val['times'];
					if($val['classroom_id']==$class['classroom_id']){
						$assign_data[$key]['classroom_name'] = $classroom['name'];
					}
					else{
						$temp = db('classroom')->where('id='.$val['classroom_id'])->find();
						$assign_data[$key]['classroom_name'] = $temp['name'];
					}
					if($val['teacher_id']==$class['teacher']){
						$assign_data[$key]['teacher_name'] = $teacher['name'];
					}
					else{
						$temp = db('teacher')->where('id='.$val['teacher_id'])->find();
						$assign_data[$key]['teacher_name'] = $temp['name'];
					}
					$assign_data[$key]['date'] = date('Y-m-d H:i:s',$val['start_time']);
					$assign_data[$key]['start_time'] = date('H:i',$val['start_time']);
					$assign_data[$key]['end_time'] = date('H:i',$val['end_time']);
					$assign_data[$key]['status'] = '1';
				}
			}
			$this->assign('data',json_encode($assign_data));
			// dump($assign_data);
			$this->assign('class',$class);
			$this->assign('classroom',$classroom);
			$this->assign('teacher',$teacher);
			$this->assign('campus',$campus);
			if(isset($param['state'])&&$param['state']=='select'){
				return $this->fetch('class_timetable_select');
			}
			else{
				return $this->fetch();
			}
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function timetable_do(){
		if($this->request->param()){
			$param = $this->request->param();
			$return_log = '';
			for($i=0;$i<$param['class_number'];$i++){
				$data['start_time'] = strtotime($param['class_date'][$i].' '.$param['starttime'][$i]);
				$data['end_time'] = strtotime($param['class_date'][$i].' '.$param['endtime'][$i]);
				if($data['start_time']>=$data['end_time']){
					$this->error('第'.$param['times'][$i].'次课结束时间不能早于开始时间');
				}
				$data['classroom_id'] = $param['classroom_id'][$i];
				$is_classroom_clash = db('class_timetable')->where('class_id<>'.$param['class_id'])->where('classroom_id='.$data['classroom_id'])->where($data['start_time'].'<end_time')->where('start_time<'.$data['end_time'])->find();
				if($is_classroom_clash){
					$clash_class = db('class')->where('id='.$is_classroom_clash['class_id'])->find();
					$this->error('第'.$param['times'][$i].'次课教室时间与'.$clash_class['name'].'的第'.$is_classroom_clash['times'].'次课冲突！');
				}
				$data['teacher_id'] = $param['teacher_id'][$i];
				$is_teacher_clash = db('class_timetable')->where('class_id<>'.$param['class_id'])->where('teacher_id='.$data['teacher_id'])->where($data['start_time'].'<end_time')->where('start_time<'.$data['end_time'])->find();
				if($is_teacher_clash){
					$clash_teacher = db('teacher')->where('id='.$is_teacher_clash['teacher_id'])->find();
					$clash_class = db('class')->where('id='.$is_teacher_clash['class_id'])->find();
					$this->error('第'.$param['times'][$i].'次课任课老师时间与'.$clash_class['name'].'的第'.$is_teacher_clash['times'].'次课冲突！');
				}
				$data['class_id'] = $param['class_id'];
				$data['class_number'] = $param['class_number'];
				$data['times'] = $param['times'][$i];
				$data['last_edit_id'] = cmf_get_current_admin_id();
				$data['last_edit_time'] = time();
				$is_exist = db('class_timetable')->where('class_id='.$param['class_id'])->where('times='.$param['times'][$i])->find();
				if($is_exist){
					$action = '第'.$param['times'][$i].'次课更新排课';
					$json_data = json_encode($data);
					$result = '成功！';
					db('class_timetable')->where('class_id='.$param['class_id'])->where('times='.$param['times'][$i])->update($data);
					self::data_log($action,$json_data,$result);
				}
				else{
					$action = '第'.$param['times'][$i].'次课新增排课';
					$json_data = json_encode($data);
					$result = '成功！';
					db('class_timetable')->insert($data);
					self::data_log($action,$json_data,$result);
				}
				$return_log = $return_log.$action.$result.'</br>';
			}
			//清除多余课次
			db('class_timetable')->where('class_id='.$param['class_id'])->where('times>'.$param['class_number'])->delete();
			$this->success($return_log);
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function timetable(){
		if($this->request->param()){
			$param = $this->request->param();
			$class = db('class')->where('id='.$param['id'])->find();
			$teacher = db('teacher')->where('id='.$class['teacher'])->find();
			$classroom = db('classroom')->where('id='.$class['classroom_id'])->find();
			$campus = db('campus')->where('id='.$classroom['campus_id'])->find();
			$teacher_tree = db('teacher')->select();
			$classroom_tree = db('classroom')->where('campus_id='.$campus['id'])->select();
			$is_class_timetable_exist = db('class_timetable')->where('class_id='.$param['id'])->order('times asc')->select()->toarray();
			if($is_class_timetable_exist){
				foreach($is_class_timetable_exist as $key=>$val){
					$is_class_timetable_exist[$key]['class_date'] = date('Y-m-d',$is_class_timetable_exist[$key]['start_time']);
					$is_class_timetable_exist[$key]['start_time'] = date('H:i',$is_class_timetable_exist[$key]['start_time']);
					$is_class_timetable_exist[$key]['end_time'] = date('H:i',$is_class_timetable_exist[$key]['end_time']);
				}
				// dump($is_class_timetable_exist);
				$this->assign('timetable',$is_class_timetable_exist);
			}
			$this->assign('teacher_tree',$teacher_tree);
			$this->assign('classroom_tree',$classroom_tree);
			$this->assign('class',$class);
			$this->assign('classroom',$classroom);
			$this->assign('teacher',$teacher);
			$this->assign('campus',$campus);
			return $this->fetch();
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function exp_class_students(){
		if($this->request->param()){
			$param = $this->request->param();
			$class = db('class')->where('id='.$param['class_id'])->find();
			$students_info = db('class_student_sign_in')->where('class_id='.$param['class_id'])->where('status=1')->alias('a')->join('student w','a.student_id = w.id')->field('student_id,name,deg,sex,phone,phone2')->select()->toarray();
			self::exp_student($class['name'].'名单',$students_info);
			// dump($students_info);
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	// 数据导入模板文件生成
	public function import_student_model_xls(){
		$students_info = [];
		self::exp_student('导入学生模板',$students_info);
	}
	
	public function exp_student($title,$data){
		$PHPExcel = new PHPExcel(); //实例化PHPExcel类，类似于在桌面上新建一个Excel表格
		$PHPSheet = $PHPExcel->getActiveSheet(); //获得当前活动sheet的操作对象
		/*右键属性所显示的信息*/
		$PHPExcel->getProperties()->setCreator("liuxg")  //作者
		   ->setLastModifiedBy("liuxg")  //最后一次保存者
		   ->setTitle($title)  //标题
		   ->setSubject($title) //主题
		   ->setDescription('导出数据')  //描述
		   ->setKeywords("excel")   //标记
		   ->setCategory("result file");  //类别
		$PHPSheet->setTitle($title); //给当前活动sheet设置名称
		$fileName = $title.date('_Y年m月d日H点i分s秒');//文件名称
		// 设置列宽
		$PHPSheet->getColumnDimension('A')->setWidth(7);
		$PHPSheet->getColumnDimension('B')->setWidth(10);
		$PHPSheet->getColumnDimension('C')->setWidth(15);
		$PHPSheet->getColumnDimension('D')->setWidth(15);
		$PHPSheet->getColumnDimension('E')->setWidth(7);
		$PHPSheet->getColumnDimension('F')->setWidth(20);
		$PHPSheet->getColumnDimension('G')->setWidth(20);
		// 设置行高
		$PHPSheet->getDefaultRowDimension()->setRowHeight(20);
		// 设置居中
		$PHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$PHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
		// 设置字体
		$PHPExcel->getDefaultStyle()->getFont()->getColor()->setARGB(\PHPExcel_Style_Color::COLOR_BLACK); // 黑色
		// 设置表头
		$PHPSheet->setCellValue('A1','序号');
		$PHPSheet->getRowDimension('1')->setRowHeight(20);
		$PHPSheet->setCellValue('B1','系统ID');
		$PHPSheet->setCellValue('C1','姓名');
		$PHPSheet->setCellValue('D1','入学年份');
		$PHPSheet->setCellValue('E1','性别');
		$PHPSheet->setCellValue('F1','联系方式');
		$PHPSheet->setCellValue('G1','备用联系方式');
		// 数据
		// $cellKey = array(
            // 'A','B','C','D','E','F','G','H','I','J','K','L','M',
            // 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
            // 'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM',
            // 'AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ'
		// );
		foreach($data as $i=>$val){
			$PHPSheet->setCellValue('A'.($i+2),$i+1);
			$PHPSheet->getRowDimension($i+2)->setRowHeight(20);
			$PHPSheet->setCellValue('B'.($i+2),$val['student_id']);
			$PHPSheet->setCellValue('C'.($i+2),$val['name']);
			$PHPSheet->setCellValue('D'.($i+2),$val['deg']);
			$PHPSheet->setCellValue('E'.($i+2),$val['sex']=='1'?'男':($val['sex']=='2'?'女':'未知'));
			$PHPSheet->setCellValue('F'.($i+2),$val['phone']);
			$PHPSheet->setCellValue('G'.($i+2),$val['phone2']);
			$log_data[$i] = $val['student_id'].$val['name'].$val['phone'];
		}
		// 日志记录
		$action = '导出数据'.$title;
		if(isset($log_data)){
			$json_data = json_encode($log_data);
		}
		else{
			$json_data = '';
		}
		$result = $fileName.'导出成功';
		self::data_log($action,$json_data,$result);
		$PHPWriter = PHPExcel_IOFactory::createWriter($PHPExcel,'Excel2007');//按照指定格式生成Excel文件，'Excel2007'表示生成2007版本的xlsx，
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出07Excel文件
		//header('Content-Type:application/vnd.ms-excel');//告诉浏览器将要输出Excel03版本文件
        header('Content-Disposition: attachment;filename="'.$fileName.'.xlsx"');//告诉浏览器输出浏览器名称
        header('Cache-Control: max-age=0');//禁止缓存
        $PHPWriter->save("php://output");
		// exit();
	}
	
	public function ver_sign_in_status($data){
		$ver_data = $data['class_id'].$data['student_id'].$data['status'].'liuxg';
		$ver_md5_data = md5($ver_data);
		if($ver_md5_data === $data['ver_code']){
			return true;
		}
		else{
			return false;
		}
	}
	
	public function get_ver_code($data){
		$ver_data = $data['class_id'].$data['student_id'].$data['status'].'liuxg';
		$ver_md5_data = md5($ver_data);
		return $ver_md5_data;
	}
	
	public function cancel_sign_in(){
		if($this->request->param()){
			$param = $this->request->param();
			if(isset($param['class_id_post'])){unset($param['class_id_post']);}
			if(!isset($param['ids'])){$this->error('请选择要退班的学生！');}
			if(!isset($param['class_id'])){$this->error('非法访问！');}
			$students = $param['ids'];
			$return_log = '';
			$class_exist = db('class')->where('id='.$param['class_id'])->find();
			if(!$class_exist){$this->error('班级不存在！');}
			$i=0;$j=0;
			foreach($students as $val){
				$data = [];
				// 校验数据库数据完整性
				$student_exist = db('student')->where('id='.$val)->find();
				if(!$student_exist){
					$j++;
					$result = 'id为'.$val.'的学生不存在！</br>';
				}
				else{
					// 验证报班数据完整性
					$sign_in_exist = db('class_student_sign_in')->where('class_id='.$param['class_id'])->where('student_id='.$val)->find();
					$ver = self::ver_sign_in_status($sign_in_exist);
					if($sign_in_exist['status']!='1'||!$ver){
						$result = $student_exist['name'].'的报班状态不正确！</br>';
						$j++;
					}
					else{
						// 退班操作
						$temp_data['class_id'] = $param['class_id'];
						$temp_data['student_id'] = $val;
						$temp_data['status'] = '3';
						$data['status'] = '3';
						$data['edit_id'] = cmf_get_current_admin_id();
						$data['last_edit_time'] = time();
						$data['ver_code'] = self::get_ver_code($temp_data);
						$res = db('class_student_sign_in')->where('id='.$sign_in_exist['id'])->update($data);
						if($res){
							$result = $student_exist['name'].'退班成功！</br>';
							$i++;
						}
						else{
							$result = $student_exist['name'].'退班失败！</br>';
							$j++;
						}
					}
				}
				$return_log = $return_log.$result;
				// 填写日志
				$action = $student_exist['name'].'退班'.$class_exist['name'];
				$json_data = json_encode($data);
				$json_old_data = json_encode($temp_data);
				self::data_log($action,$json_data,$result,$json_old_data);
			}
			$this->success('操作完成！</br>共退班'.count($students).'名，成功'.$i.'名，失败'.$j.'名</br>'.$return_log);
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function students_class(){
		if($this->request->param()){
			$param = $this->request->param();
			$class_id = $param['id'];
			$class_info = db('class')->where('id='.$class_id)->find();
			$students_info = db('class_student_sign_in')->where('class_id='.$class_id)->where('status=1')->alias('a')->join('student w','a.student_id = w.id')->field('student_id,name,deg,sex,phone,phone2,note,onion')->select();
			// dump($students_info);
			$this->assign('class_info',$class_info);
			$this->assign('students_info',$students_info);
			return $this->fetch();
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function sign_in_post(){
		$param = $this->request->param();
		if($param&&isset($param['class_id_post'])){
			if($param['class_id_post'] == ''){
				$this->error('请选择要报名的班级！');
			}
			if(!is_numeric($param['class_id_post'])){
				$this->error('非法访问！');
			}
			// if(count($param['class_id_post'])>1){
				// $this->error('一次只能报名一个班级！');
			// }
			if(isset($param['ids'])&&count($param['ids']>0)){
				$i = 0;$j = 0;$return_log = '';
				$class = db('class')->where('id='.$param['class_id_post'])->find();
				$data['class_id'] = $param['class_id_post'];
				foreach($param['ids'] as $val){
					$student = db('student')->where('id='.$val)->find();
					$data['student_id'] = $val;
					$is_exist = db('class_student_sign_in')->where('class_id='.$param['class_id_post'])->where('student_id='.$val)->find();
					$already_sign = db('class_student_sign_in')->where('class_id='.$param['class_id_post'])->where('status=1')->count();
					if($is_exist){
						if($is_exist['status']==1){
							$result = '学生'.$student['name'].'已报名'.$class['name'].'!';
							$j++;
						}
						else{
							$data['status'] = '1';
							$temp_data['status'] = '1';
							$temp_data['edit_id'] = cmf_get_current_admin_id();
							$temp_data['last_edit_time'] = time();
							$temp_data['ver_code'] = self::get_ver_code($data);
							$res = db('class_student_sign_in')->where('id='.$is_exist['id'])->update($temp_data);
							if($res){
								$result = $student['name'].'报名成功！';
								$i++;
							}
							else{
								$result = $student['name'].'报名失败！';
								$j++;
							}
						}
					}
					// elseif($already_sign>=$class['student_number']){
						// $result = $student['name'].'报名失败！'.$class['name'].'名额已满!';
						// $j++;
					// }
					else{
						$data['status'] = '1';
						$data['create_id'] = cmf_get_current_admin_id();
						$data['edit_id'] = cmf_get_current_admin_id();
						$data['last_edit_time'] = time();
						$data['ver_code'] = self::get_ver_code($data);
						$res = db('class_student_sign_in')->insert($data);
						if($res){
							$result = $student['name'].'报名成功！';
							$i++;
						}
						else{
							$result = $student['name'].'报名失败！';
							$j++;
						}
					}
					$return_log = $return_log.'</br>'.$result;
					// 填写日志
					$action = $student['name'].'报名'.$class['name'];
					$json_data = json_encode($data);
					self::data_log($action,$json_data,$result);
					// dump($data);
					// $this->error(json_encode($data));
				}
				$this->success('报名操作结束，共操作'.count($param['ids']).'个，成功'.$i.'个，失败'.$j.'个'.$return_log,'','',5);
			}
			else{
				$this->error('请选择要报名的学生！');
			}
			
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function select()
    {
			$param = $this->request->param();
			// $classroom = db('classroom')->where('campus_id='.$param['id'])->select();
			$result = db('class')
			->alias('c')
			->join('classroom w','c.classroom_id = w.id')
			->join('teacher t','c.teacher = t.id')
			->field('c.id as id,c.name as name,w.name as classroom_id,t.name as teacher,c.class_number as class_number,c.student_number as student_number,w.map_img as map_img')
			->order('id asc')->select();
			$campus = db('campus')->where('id='.$param['id'])->find();
			$param['campus_name'] = $campus['name'];
			$category_tree_array = db('school_category')->where('status=1')->select()->toarray();
			$category_tree = self::get_tree($category_tree_array,'0');
			// dump($category_tree);exit();
			$this->assign("category_tree",json_encode($category_tree));
			// $this->assign('page', $result->render());
			$this->assign("class_info", $result);
			$this->assign("param", $param);
			return $this->fetch();
    }
	
	public function get_tree($data,$parent_id){
		$tree = [];$i=0;
		foreach($data as $val){
			if($val['parent_id'] == $parent_id){
				$tree[$i]['text'] = $val['name'];
				$tree[$i]['nodes'] = self::get_tree($data,$val['id']);
				if(empty($tree[$i]['nodes'])){
					unset($tree[$i]['nodes']);
				}
				$href = db('school_category_post')->where('category_id='.$val['id'])->field('post_id')->select()->toarray();
				$tree[$i]['href'] = json_encode($href);
				$i++;
			}
		}
		return $tree;
	}
	
	public function find_class(){
		if($this->request->param()){
			$param = $this->request->param();
			// $classroom = db('classroom')->where('campus_id='.$param['id'])->select();
			$result = db('class')->alias('a')->order('a.id asc')->join('classroom w','w.id=a.classroom_id&&w.campus_id='.$param['id'])->join('teacher t','t.id=a.teacher')->field('a.id as id,a.name as name,w.name as classroom_id,t.name as teacher,class_number,student_number,map_img')->select();
			$campus = db('campus')->where('id='.$param['id'])->find();
			$param['campus_name'] = $campus['name'];
			$category_tree_array = db('school_category')->where('status=1')->select()->toarray();
			$category_tree = self::get_tree($category_tree_array,'0');
			// dump($category_tree);exit();
			$this->assign("category_tree",json_encode($category_tree));
			// $this->assign('page', $result->render());
			$this->assign("class_info", $result);
			$this->assign("param", $param);
			return $this->fetch();
		}
		else{
			$this->error('非法访问！');
		}
	}
	/**
     * 新增/编辑班级
     */
	public function add_class(){
		if($this->request->param()){
			$param = $this->request->param();
			$campus = db('campus')->where('id='.$param['id'])->find();
			$teacher = db('teacher')->select();
			$teacher_tree = '';$classroom_tree = '';
			foreach($teacher as $val){
				$teacher_tree = $teacher_tree.'<option value="'.$val['id'].'">'.$val['name'].'</option>';
			}
			$classroom = db('classroom')->where('campus_id='.$param['id'])->select();
			foreach($classroom as $val){
				$classroom_tree = $classroom_tree.'<option value="'.$val['id'].'">'.$val['name'].'</option>';
			}
			$this->assign("teacher_tree",$teacher_tree);
			$this->assign("classroom_tree",$classroom_tree);
			$this->assign('campus',$campus);
			return $this->fetch();
		}
		else{
			return $this->error('非法访问！');
		}
	}
	
	public function add_class_post(){
		if($this->request->param()){
			$param = $this->request->param();
			//校区是否存在
			$is_exist = db('campus')->where('id='.$param['campus_id'])->find();
			if(!$is_exist){
				$this->error('校区不存在！');
			}
			//教室是否存在
			$classroom = db('classroom')->where(['id'=>$param['classroom_id']])->find();
			if(!$classroom){
				$this->error('教室不存在！');
			}
			//数据整理
			$param['create_id'] = cmf_get_current_admin_id();
			$param['edit_id'] = cmf_get_current_admin_id();
			$param['create_time'] = time();
			$param['edit_time'] = time();
			if(!isset($param['student_number'])||$param['student_number']==''){
				$param['student_number'] = $classroom['max_count'];
			}
			unset($param['campus_id']);
			$res = db('class')->insertGetId($param);
			if($res){
				// 分类表
				if (is_string($param['categories'])) {
					$categories = explode(',', $param['categories']);
				}
				$category_data['post_id'] = $res;
				foreach($categories as $val){
					$category_data['category_id'] = $val;
					db('school_category_post')->insert($category_data);
				}
				// 填写日志
				$action = $is_exist['name'].'添加班级';
				$json_data = json_encode($param);
				$result = '成功';
				self::data_log($action,$json_data,$result);
				
			$this->success($is_exist['name'].'添加班级成功',url('Classroom/campus'));
			}
			else{
				$this->error('系统错误！errcode：-701');
			}
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function edit_class(){
		if($this->request->param()){
			$param = $this->request->param();
			$class = db('class')->where('id='.$param['id'])->find();
			$classroom = db('classroom')->where('id='.$class['classroom_id'])->find();
			$campus = db('campus')->where('id='.$classroom['campus_id'])->find();
			$teacher = db('teacher')->select();
			$teacher_tree = '';$classroom_tree = '';
			foreach($teacher as $val){
				$teacher_tree = $teacher_tree.'<option value="'.$val['id'].'" '.($val['id']==$class['teacher']?'selected="selected"':'').'>'.$val['name'].'</option>';
			}
			$classroom_all = db('classroom')->where('campus_id='.$classroom['campus_id'])->select();
			foreach($classroom_all as $val){
				$classroom_tree = $classroom_tree.'<option value="'.$val['id'].'" '.($val['id']==$class['classroom_id']?'selected="selected"':'').'>'.$val['name'].'</option>';
			}
			// 分类表
			$categories = db('school_category_post')->where('post_id='.$param['id'])->select()->toarray();
			$class['category_titles'] = '';
			foreach($categories as $val){
				$category_name = db('school_category')->where('id='.$val['category_id'])->find();
				$class['category_titles'] = $class['category_titles'].' '.$category_name['name'];
			}
			$this->assign("teacher_tree",$teacher_tree);
			$this->assign("classroom_tree",$classroom_tree);
			$this->assign('campus',$campus);
			$this->assign('param',$class);
			return $this->fetch();
		}
		else{
			return $this->error('非法访问！');
		}
	}
	
	public function edit_class_post(){
		if($this->request->param()){
			$param = $this->request->param();
			//班级是否存在
			$is_exist = db('class')->where('id='.$param['class_id'])->find();
			if(!$is_exist){
				$this->error('班级不存在！');
			}
			//数据整理
			$param['edit_id'] = cmf_get_current_admin_id();
			$param['edit_time'] = time();
			$data = $param;
			unset($data['class_id']);
			// 分类
			if (is_string($param['categories'])) {
					$categories = explode(',', $param['categories']);
				}
			$oldCategoryIds_array        = db('school_category_post')->where('post_id='.$param['class_id'])->field('category_id')->select()->toarray();
			if(!empty($oldCategoryIds_array)){
				foreach($oldCategoryIds_array as $key=>$val){
					$oldCategoryIds[$key] = $val['category_id'];
				}
			}
			else{
				$oldCategoryIds = array();
			}
			$sameCategoryIds       = array_intersect($categories, $oldCategoryIds);
			$needDeleteCategoryIds = array_diff($oldCategoryIds, $sameCategoryIds);
			$newCategoryIds        = array_diff($categories, $sameCategoryIds);
			foreach($needDeleteCategoryIds as $val){
				db('school_category_post')->where('post_id='.$param['class_id'])->where('category_id='.$val)->delete();
			}
			foreach($newCategoryIds as $val){
				$newCategoryIds_data['post_id'] = $param['class_id'];
				$newCategoryIds_data['category_id'] = $val;
				db('school_category_post')->insert($newCategoryIds_data);
			}
			$res = db('class')->where('id='.$param['class_id'])->update($data);
			if($res){
				// 填写日志
				$action = '编辑班级'.$is_exist['name'];
				$json_data = json_encode($param);
				$result = '成功';
				$old_json_data = json_encode($is_exist);
				self::data_log($action,$json_data,$result,$old_json_data);
				
			$this->success($is_exist['name'].'编辑成功',url('Classroom/campus'));
			}
			else{
				$this->error('系统错误！errcode：-702');
			}
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function class_attendance(){
		if($this->request->param()){
			$param = $this->request->param();
			if(!isset($param['timetable_id'])){
				if(!isset($param['class_id'])){
					$this->error('非法访问！');
				}
				else{
					$find_param = db('class_timetable')->where(['class_id'=>$param['class_id']])->find();
					$param['timetable_id'] = $find_param['id'];
				}
			}
			// 本班学生数据
			$student_data = db('class_timetable')
			->alias('a')
			->where(['a.id'=>$param['timetable_id']])
			->join('class_student_sign_in s','s.class_id = a.class_id')
			->join('student_attendance att','s.student_id = att.student_id AND att.timetable_id = a.id','LEFT')
			->join('student b','b.id = s.student_id OR b.id = att.student_id')
			->order('convert(b.name using gbk) asc')
			->field('b.name as name,b.id as student_id,b.phone as phone,b.phone2 as phone2,att.code as code,a.id as timetable_id')
			->select()->toArray();
			// 调入学生数据
			$student_attendance_data = db('student_attendance')
			->alias('att')
			->where(['target'=>$param['timetable_id']])
			->join('student b','b.id = att.student_id')
			->order('convert(b.name using gbk) asc')
			->field('b.name as name,b.id as student_id,b.phone as phone,b.phone2 as phone2,5 as code,att.timetable_id as timetable_id,att.more as more')
			->select()->toArray();
			//合并数据
			$merge_data = array_merge($student_data,$student_attendance_data);
			foreach($merge_data as &$vo){
				switch($vo['code']){
					case -3:
						$vo['attendance_status'] = '缺勤';
						break;
					case -2:
						$vo['attendance_status'] = '早退';
						break;
					case -1:
						$vo['attendance_status'] = '迟到';
						break;
					case 0:
						$vo['attendance_status'] = '未考勤';
						break;
					case 1:
						$vo['attendance_status'] = '正常出勤';
						break;
					case 2:
						$vo['attendance_status'] = '调课调出';
						break;
					case 3:
						$vo['attendance_status'] = '请假';
						break;
					case 5:
						$vo['attendance_status'] = '调课调入';
						$more_data = json_decode($vo['more'],true);
						switch($more_data['attendance_status']){
							case -3:
								$vo['attendance_status'] = $vo['attendance_status'].'(缺勤)';
								break;
							case -2:
								$vo['attendance_status'] = $vo['attendance_status'].'(早退)';
								break;
							case -1:
								$vo['attendance_status'] = $vo['attendance_status'].'(迟到)';
								break;
							case 0:
							case null:
								$vo['attendance_status'] = $vo['attendance_status'].'(未考勤)';
								break;
							case 1:
								$vo['attendance_status'] = $vo['attendance_status'].'(正常出勤)';
								break;
							case 3:
								$vo['attendance_status'] = $vo['attendance_status'].'(请假)';
								break;
							default:
								$vo['attendance_status'] = $vo['attendance_status'].'(未考勤)';
						}
						break;
					default:
						$vo['attendance_status'] = '未考勤';
				}
			}
			// 课表数据
			$timetable_data = db('class_timetable')
			->where(['a.id'=>$param['timetable_id']])
			->alias('a')
			->join('teacher t','t.id = a.teacher_id')
			->join('class c','c.id = class_id')
			->join('classroom d','d.id = a.classroom_id')
			->field('a.id as id,a.class_number as class_number,a.times as times,a.start_time as start_time,a.end_time as end_time,t.name as teacher_name,c.name as class_name,d.name as classroom_name,c.id as class_id')
			->find();
			// 其他课次课表数据
			$times_data = db('class_timetable')->where(['class_id'=>$timetable_data['class_id']])->select();
			$this->assign('times_data',$times_data);
			$this->assign('timetable_data',$timetable_data);
			$this->assign('student_data',$merge_data);
			if(cmf_is_mobile()){
				return $this->fetch('class_attendance_mobile');
			}
			else{
				return $this->fetch();
			}
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function onekey_attendance(){
		if($this->request->param()){
			$param = $this->request->param();
			// 本班学生数据
			$student_data = db('class_timetable')
			->alias('a')
			->where(['a.id'=>$param['timetable_id']])
			->join('class_student_sign_in s','s.class_id = a.class_id')
			->join('student_attendance att','s.student_id = att.student_id AND att.timetable_id = a.id','LEFT')
			->join('student b','b.id = s.student_id OR b.id = att.student_id')
			->order('convert(b.name using gbk) asc')
			->field('b.id as student_id,att.target as target,att.code as code')
			->select()->toArray();
			// 调入学生数据
			$student_attendance_data = db('student_attendance')
			->alias('att')
			->where(['target'=>$param['timetable_id']])
			->join('student b','b.id = att.student_id')
			->order('convert(b.name using gbk) asc')
			->field('b.id as student_id,timetable_id,att.target as target,5 as code')
			->select()->toArray();
			//合并数据
			$merge_data = array_merge($student_data,$student_attendance_data);
			$update_data = [];
			$insert_data = [];
			foreach($merge_data as $vo){
				$vo['status'] = '1';
				$vo['edit_id'] = cmf_get_current_admin_id();
				$vo['last_edit_time'] = time();
				switch($vo['code']){
					case '0':
						$vo['code'] = 1;
						$vo['timetable_id'] = $param['timetable_id'];
						array_push($update_data,$vo);
						break;
					case null:
						$vo['code'] = 1;
						$vo['timetable_id'] = $param['timetable_id'];
						array_push($insert_data,$vo);
						break;
					case '5':
						$vo['more'] = json_encode(['attendance_status'=>1]);
						$vo['code'] = '2';
						array_push($update_data,$vo);
						break;
				}
			}
			$res = db('student_attendance')->insertAll($insert_data);
			foreach($update_data as $data_vo){
				db('student_attendance')->where(['student_id'=>$data_vo['student_id'],'timetable_id'=>$data_vo['timetable_id']])->update($data_vo);
			}
			if($res){
				$this->success('一键签到成功！');
			}
			else{
				$this->error('你是不是已经帮大家签过到了？');
			}
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function class_blog_list(){
		if($this->request->param()){
			$param = $this->request->param();
			$page = isset($param['page'])?$param['page']:1;
			if(!isset($param['timetable_id'])){
				if(!isset($param['class_id'])){
					$this->error('非法访问！');
				}
				else{
					$class_id = $param['class_id'];
					$class = db('class')->where(['id'=>$param['class_id']])->find();
					$this_timetable_data = db('class_timetable')->where(['class_id'=>$param['class_id']])->find();
					$this_timetable_data['times'] = 0;
					$this_timetable_data['class_name'] = $class['name'];

					$class_timetable_list = db('class_timetable')->where(['class_id'=>$param['class_id']])->select();
					// 班级blog数据集
					$blog = new class_blogModel();
					$where = [
						'a.class_id'=>$param['class_id'],
					];
					
					$join = [
						['user u','u.id = a.user_id'],
					];
					if(isset($param['tags'])){
						array_push($join,['blog_tag_post tag','a.id = tag.blog_id AND tag.tag_id ='.$param['tags']]);
					}
					
					$blog_data = $blog
					->alias('a')
					->where($where)
					->join($join)
					->field('u.user_nickname as user_nickname,title,update_time,delete_time,content,is_top,post_hits,a.id as id,avatar,is_top,a.more as more')
					->limit(5)
					->page($page)
					->order('is_top desc,delete_time desc,update_time desc')
					->select()->toArray();
				}
			}
			else{
				// 当次课表信息
				$this_timetable_data = db('class_timetable')
				->alias('a')
				->where(['a.id'=>$param['timetable_id']])
				->join('class b','b.id = a.class_id')
				->join('classroom c','c.id = a.classroom_id')
				->join('teacher t','t.id = a.teacher_id')
				->field('a.id as id,a.class_id as class_id,a.class_number as class_number,a.times as times,a.start_time as start_time,a.end_time as end_time,b.name as class_name,c.name as classroom_name,t.name as teacher_name')
				->find();
				// 班级课表数据列表
				$class_timetable_list = db('class_timetable')->where(['class_id'=>$this_timetable_data['class_id']])->select();
				$class_id = $this_timetable_data['class_id'];
				// 班级blog数据集
				$blog = new class_blogModel();
				$where = [
					'a.class_id'=>$this_timetable_data['class_id'],
					'a.timetable_id'=>$param['timetable_id'],
				];
				
				$join = [
					['user u','u.id = a.user_id'],
				];
				if(isset($param['tags'])){
					array_push($join,['blog_tag_post tag','a.id = tag.blog_id AND tag.tag_id ='.$param['tags']]);
				}
				
				$blog_data = $blog
				->alias('a')
				->where($where)
				->join($join)
				->field('u.user_nickname as user_nickname,title,update_time,delete_time,content,is_top,post_hits,a.id as id,avatar,is_top,a.more as more')
				->limit(5)
				->page($page)
				->order('is_top desc,delete_time desc,update_time desc')
				->select()->toArray();
			}
			// 浏览量自增
			foreach($blog_data as $hits_inc){
				$blog->where(['id'=>$hits_inc['id']])->setInc('post_hits',rand(1,9));
			}
			// 标签数据
			$tags_data = db('blog_tag')->where(['class_id'=>$class_id])->select();
			// 输出内容
			if($this->request->isAjax()){
				foreach($blog_data as &$blog_data_vo){
					$blog_data_vo['update_time'] = date('Y-m-d H:i:s',$blog_data_vo['update_time']);
					$blog_data_vo['post_hits'] += 1;
				}
				$ajaxReturn['data'] = $blog_data;
				$ajaxReturn['page'] = $page;
				return json($ajaxReturn);
			}
			else{
				// dump($blog_data);
				$this->assign('tags_data',$tags_data);
				$this->assign('param',$param);
				$this->assign('blog_data',$blog_data);
				$this->assign('this_timetable_data',$this_timetable_data);
				$this->assign('class_timetable_list',$class_timetable_list);
				return $this->fetch();
			}
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function class_blog_add(){
		if($this->request->param()){
			//费尽心思获取到最近一次课的课表
			$param = $this->request->param();
			if(!isset($param['timetable_id'])){
				$is_get_timetable_id = db('class_timetable')->where(['class_id'=>$param['class_id']])->whereTime('start_time', 'd')->find();
				if(!$is_get_timetable_id){
					$is_get_timetable_id = db('class_timetable')->where(['class_id'=>$param['class_id']])->whereTime('start_time', 'w')->find();
				}
				if(!$is_get_timetable_id){
					$is_get_timetable_id = db('class_timetable')->where(['class_id'=>$param['class_id']])->whereTime('start_time', 'm')->find();
				}
				if(!$is_get_timetable_id){
					$is_get_timetable_id = db('class_timetable')->where(['class_id'=>$param['class_id']])->whereTime('start_time', 'y')->find();
				}
				if(!$is_get_timetable_id){
					$is_get_timetable_id = db('class_timetable')->where(['class_id'=>$param['class_id']])->find();
				}
				if(!$is_get_timetable_id){
					$this->error('当前班级未排课，请排课后重试！');
				}
				else{
					$param['timetable_id'] = $is_get_timetable_id['id'];
				}
			}
			else{
				$is_get_timetable_id = db('class_timetable')->where(['id'=>$param['timetable_id']])->find();
				$param['class_id'] = $is_get_timetable_id['class_id'];
			}
			//查询课次列表
			$class_data = db('class')->where(['id'=>$param['class_id']])->find();
			$is_get_timetable_id['class_name'] = $class_data['name'];
			$class_timetable_list = db('class_timetable')->where(['class_id'=>$param['class_id']])->select();
			
			// 获取标签
			$blog_tags = db('blog_tag')->where(['class_id'=>$param['class_id']])->select();
			
			$this->assign('blog_tags',$blog_tags);
			
			$this->assign('class_timetable_list',$class_timetable_list);
			$this->assign('this_timetable_data',$is_get_timetable_id);
			return $this->fetch();
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function class_blog_add_post(){
		if($this->request->param()){
			$data   = $this->request->param();
            $post   = $data['post'];
			unset($data['post']['tags']);
			
            $portalPostModel = new class_blogModel();

            if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
                $data['post']['more']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
                }
            }

            if (!empty($data['file_names']) && !empty($data['file_urls'])) {
                $data['post']['more']['files'] = [];
                foreach ($data['file_urls'] as $key => $url) {
                    $fileUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
                }
            }

            $portalPostModel->adminAddArticle($data['post']);

            $data['post']['id'] = $portalPostModel->id;
			
			// 标签数据
			$array_tags = explode(',',$post['tags']);
			if(isset($array_tags)&&count($array_tags)>0&&$array_tags[0]!=''){
				foreach($array_tags as $key=>$array_tags_vo){
					$tags_data[$key]['tag_id'] = $array_tags_vo;
					$tags_data[$key]['blog_id'] = $portalPostModel->id;
				}
				db('blog_tag_post')->insertAll($tags_data);
			}
            $this->success('添加成功!', url('admin/class/class_blog_edit', ['id' => $portalPostModel->id]));
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function class_blog_edit(){
		if($this->request->param()){
			$param = $this->request->param();
			//查询原有数据
			$portalPostModel = new class_blogModel();
			$edit_data            = $portalPostModel->where('id', $param['id'])->find();
			//查询课次列表
			// $edit_data = db('class_blog')->where(['id'=>$param['id']])->find();
			$class_data = db('class')->where(['id'=>$edit_data['class_id']])->find();
			if(isset($edit_data['timetable_id'])&&$edit_data['timetable_id']>0){
				$is_get_timetable_id = db('class_timetable')->where(['id'=>$edit_data['timetable_id']])->find();
			}
			else{
				$is_get_timetable_id['times'] = 0;
				$is_get_timetable_id['id'] = 0;
				$is_get_timetable_id['class_id'] = $edit_data['class_id'];
			}
			$is_get_timetable_id['class_name'] = $class_data['name'];
			$class_timetable_list = db('class_timetable')->where(['class_id'=>$edit_data['class_id']])->select();
			
			// 获取标签
			$blog_tags = db('blog_tag')->where(['class_id'=>$edit_data['class_id']])->select()->toArray();
			$blog_selected = db('blog_tag_post')->where(['blog_id'=>$param['id']])->select()->toArray();
			foreach($blog_selected as $temp_key=>$temp_vo){
				$temp_selected[$temp_key] = $temp_vo['tag_id'];
			}
			if(isset($temp_selected)){
				$is_get_timetable_id['tags'] = count($temp_selected)>1?implode(',',$temp_selected):$temp_selected[0];
				
				foreach($blog_tags as &$is_selected){
					foreach($temp_selected as $blog_ids){
						if($blog_ids==$is_selected['id']){
							$is_selected['selected'] = 1;
						}
					}
				}
			}
			$this->assign('blog_tags',$blog_tags);
			$this->assign('post', $edit_data);
			
			$this->assign('class_timetable_list',$class_timetable_list);
			$this->assign('this_timetable_data',$is_get_timetable_id);
			return $this->fetch();
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function class_blog_edit_post(){
		if ($this->request->isPost()) {
            $data   = $this->request->param();
            $post   = $data['post'];

            $portalPostModel = new class_blogModel();

            if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
                $data['post']['more']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
                }
            }

            if (!empty($data['file_names']) && !empty($data['file_urls'])) {
                $data['post']['more']['files'] = [];
                foreach ($data['file_urls'] as $key => $url) {
                    $fileUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
                }
            }

            $portalPostModel->adminEditArticle($data['post'],$data['blog_id']);
			
			// 标签数据
			$array_tags = explode(',',$post['tags']);
			$old_tags = db('blog_tag_post')->where(['blog_id'=>$data['blog_id']])->field('tag_id')->select()->toArray();
			if($old_tags){
				foreach($old_tags as $old_tags_key=>$old_tags_vo){
					$array_old_tags[$old_tags_key] = (string)$old_tags_vo['tag_id'];
				}
			$need_insert = array_diff($array_tags,$array_old_tags);
			$need_delete = array_diff($array_old_tags,$array_tags);
			}
			else{
				$need_insert = $array_tags;
			}
			if($array_tags[0]==''){
				$need_insert = array();
			}
			if(isset($need_insert)&&count($need_insert)>0){
				foreach($need_insert as $key=>$array_tags_vo){
					$tags_data[$key]['tag_id'] = $array_tags_vo;
					$tags_data[$key]['blog_id'] = $data['blog_id'];
				}
				db('blog_tag_post')->insertAll($tags_data);
			}
			if(isset($need_delete)&&count($need_delete)>0){
				foreach($need_delete as $need_delete_vo){
					db('blog_tag_post')->where(['tag_id'=>$need_delete_vo,'blog_id'=>$data['blog_id']])->delete();
				}
			}
            $this->success('保存成功!');

        }
	}
	
	public function update_tags(){
		if($this->request->param()){
			$param = $this->request->param();
			if(isset($param['tags_id'])){
				
			}
			else{
				$data['class_id']=$param['class_id'];
				$data['parent_id'] = 0;
				$data['name'] = $param['name'];
				$data['delete_time'] = 0;
				$data['list_order'] = 10000;
				$data['more'] = '';
				if(db('blog_tag')->where($param)->find()){
					// 重复提交
					$ajaxReturn['code'] = 2;
					return json($ajaxReturn);
				}
				else{
					$res = db('blog_tag')->insertGetId($data);
					if($res){
						$ajaxReturn['code'] = 1;
						$ajaxReturn['id'] = $res;
						return json($ajaxReturn);
					}
					else{
						$ajaxReturn['code'] = 0;
						return json($ajaxReturn);
					}
				}
			}
		}
		else{
			$this->error('非法访问！');
		}
	}
}
